<template>
	<view class="matchmaker-list-page">
		<!-- 顶部导航栏 -->
		<view class="nav-bar">
			<view class="nav-left" @click="goBack">
				<text class="back-icon">←</text>
			</view>
			<view class="nav-title">红娘服务</view>
			<view class="nav-right"></view>
		</view>

		<!-- 筛选栏 -->
		<view class="filter-bar">
			<scroll-view scroll-x class="filter-scroll">
				<view class="filter-item" 
					:class="{ active: filterType === null }" 
					@click="filterByType(null)">
					全部
				</view>
				<view class="filter-item" 
					:class="{ active: filterType === 2 }" 
					@click="filterByType(2)">
					全职红娘
				</view>
				<view class="filter-item" 
					:class="{ active: filterType === 1 }" 
					@click="filterByType(1)">
					兼职红娘
				</view>
			</scroll-view>
		</view>

		<!-- 红娘列表 -->
		<scroll-view class="matchmaker-scroll" 
			scroll-y 
			@scrolltolower="loadMore"
			:lower-threshold="100">
			<view class="matchmaker-list">
				<view class="matchmaker-card" 
					v-for="(item, index) in matchmakerList" 
					:key="item.matchmakerId"
					@click="goToDetail(item.matchmakerId)">
					<!-- 左侧头像 -->
					<view class="avatar-section">
						<image :src="getAvatarUrl(item.avatarUrl)" 
							class="avatar" 
							mode="aspectFill"
							@error="handleImageError(item)"
							@load="handleImageLoad(item)">
						</image>
						<view class="avatar-placeholder" v-if="shouldShowPlaceholder(item)">
							<text class="placeholder-icon">👤</text>
						</view>
						<view class="level-badge" :class="'level-' + (item.level || 1)">
							{{ item.levelName || '青铜红娘' }}
						</view>
					</view>

					<!-- 右侧信息 -->
					<view class="info-section">
						<!-- 姓名和标签 -->
						<view class="name-row">
							<text class="name">{{ item.realName }}</text>
							<view class="type-tag" :class="item.matchmakerType === 2 ? 'formal' : 'parttime'">
								{{ item.typeName || '兼职红娘' }}
							</view>
						</view>

						<!-- 成功案例数 -->
						<view class="stats-row">
							<text class="stats-icon">💑</text>
							<text class="stats-text">成功撮合 {{ item.successCouples || 0 }} 对</text>
						</view>

						<!-- 地址 -->
						<view class="location-row" v-if="item.cityName">
							<text class="location-icon">📍</text>
							<text class="location-text">{{ item.cityName }} {{ item.areaName || '' }}</text>
						</view>

						<!-- 简介 -->
						<view class="profile-row" v-if="item.profile">
							<text class="profile-text">{{ item.profile }}</text>
						</view>

						<!-- 操作按钮 -->
						<view class="action-row">
							<view class="contact-btn" @click.stop="contactMatchmaker(item)">
								<text class="btn-icon">📞</text>
								<text class="btn-text">联系TA</text>
							</view>
							<view class="detail-btn">
								<text class="btn-text">查看详情</text>
								<text class="arrow">→</text>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 加载状态 -->
			<view class="load-status">
				<text v-if="loading" class="loading-text">加载中...</text>
				<text v-else-if="noMore" class="nomore-text">没有更多了</text>
			</view>

			<!-- 空状态 -->
			<view class="empty-state" v-if="!loading && matchmakerList.length === 0">
				<text class="empty-icon">🤷‍♀️</text>
				<text class="empty-text">暂无红娘数据</text>
			</view>
		</scroll-view>

		<!-- 底部占位 -->
		<view class="bottom-placeholder"></view>
	</view>
</template>

<script>
import api from '@/utils/api.js'
import { DEFAULT_IMAGES } from '@/config/index.js'

export default {
	data() {
		return {
			// 筛选条件
			filterType: 2, // 默认显示全职红娘
			
			// 红娘列表
			matchmakerList: [],
			
			// 分页信息
			pageNum: 1,
			pageSize: 10,
			total: 0,
			
			// 加载状态
			loading: false,
			noMore: false,
			
			// 默认头像
			defaultAvatar: DEFAULT_IMAGES.avatar
		}
	},

	onLoad(options) {
		// 从参数获取筛选类型
		if (options.type) {
			this.filterType = parseInt(options.type)
		}
		
		// 加载红娘列表
		this.loadMatchmakerList()
	},

	methods: {
		/**
		 * 加载红娘列表
		 */
		async loadMatchmakerList(isLoadMore = false) {
			if (this.loading) return
			
			this.loading = true
			
			try {
				// 如果不是加载更多，重置页码
				if (!isLoadMore) {
					this.pageNum = 1
					this.matchmakerList = []
					this.noMore = false
				}
				
				const params = {
					pageNum: this.pageNum,
					pageSize: this.pageSize,
					matchmakerType: this.filterType,
					orderBy: 'success_couples',
					orderType: 'desc'
				}
				
				const result = await api.matchmaker.getList(params)
				
				if (result && result.records) {
					if (isLoadMore) {
						this.matchmakerList = [...this.matchmakerList, ...result.records]
					} else {
						this.matchmakerList = result.records
					}
					
					this.total = result.total
					
					// 判断是否还有更多数据
					if (this.matchmakerList.length >= this.total) {
						this.noMore = true
					}
				}
			} catch (error) {
				console.error('加载红娘列表失败:', error)
				uni.showToast({
					title: '加载失败，请重试',
					icon: 'none'
				})
			} finally {
				this.loading = false
			}
		},

		/**
		 * 加载更多
		 */
		loadMore() {
			if (this.loading || this.noMore) return
			
			this.pageNum++
			this.loadMatchmakerList(true)
		},

		/**
		 * 按类型筛选
		 */
		filterByType(type) {
			if (this.filterType === type) return
			
			this.filterType = type
			this.loadMatchmakerList()
		},

		/**
		 * 跳转到详情页
		 */
		goToDetail(matchmakerId) {
			uni.navigateTo({
				url: `/pages/matchmakers/detail?id=${matchmakerId}`
			})
		},

		/**
		 * 联系红娘
		 */
		contactMatchmaker(matchmaker) {
			// 防御性检查
			if (!matchmaker || !matchmaker.phone) {
				uni.showToast({
					title: '红娘联系方式不可用',
					icon: 'none'
				})
				return
			}
			
			uni.showModal({
				title: '联系红娘',
				content: `电话：${matchmaker.phone}\n邮箱：${matchmaker.email || '未提供'}`,
				confirmText: '拨打电话',
				cancelText: '取消',
				success: (res) => {
					if (res.confirm) {
						uni.makePhoneCall({
							phoneNumber: matchmaker.phone,
							fail: () => {
								uni.showToast({
									title: '拨号失败',
									icon: 'none'
								})
							}
						})
					}
				}
			})
		},

		/**
		 * 获取头像URL
		 */
		getAvatarUrl(avatarUrl) {
			if (avatarUrl) {
				// 如果是完整URL（MinIO生成的预签名URL或其他有效URL）
				if (avatarUrl.startsWith('http')) {
					// 检查是否是无效的placeholder URL
					if (avatarUrl.includes('placeholder')) {
						console.log('检测到placeholder URL，使用默认头像')
						return this.defaultAvatar
					}
					return avatarUrl
				}
				// 如果是相对路径，添加基础路径
				if (!avatarUrl.startsWith('/')) {
					return `/static/${avatarUrl}`
				}
				return avatarUrl
			}
			// 无头像URL时使用默认头像
			return this.defaultAvatar
		},

		/**
		 * 判断是否显示占位符
		 */
		shouldShowPlaceholder(item) {
			// 防御性检查：确保item存在
			if (!item || typeof item !== 'object') {
				return true // 无效数据时显示占位符
			}
			// 如果没有头像URL，或头像加载失败，显示占位符
			return !item.avatarUrl || item.imageLoadError || 
				   (item.avatarUrl && item.avatarUrl.includes('placeholder'))
		},

		/**
		 * 图片加载成功处理
		 */
		handleImageLoad(item) {
			// 防御性检查：确保item存在且是对象
			if (!item || typeof item !== 'object') {
				console.warn('handleImageLoad: item参数无效', item)
				return
			}
			this.$set(item, 'imageLoadError', false)
			this.$set(item, 'imageLoaded', true)
		},

		/**
		 * 图片加载错误处理
		 */
		handleImageError(item) {
			// 防御性检查：确保item存在且是对象
			if (!item || typeof item !== 'object') {
				console.warn('handleImageError: item参数无效', item)
				return
			}
			console.log('头像加载失败:', item.realName, item.avatarUrl)
			this.$set(item, 'imageLoadError', true)
			this.$set(item, 'imageLoaded', false)
		},

		/**
		 * 返回
		 */
		goBack() {
			uni.navigateBack({
				fail: () => {
					uni.switchTab({
						url: '/pages/index/index'
					})
				}
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.matchmaker-list-page {
	min-height: 100vh;
	background-color: #F5F5F5;
}

/* 导航栏 */
.nav-bar {
	display: flex;
	justify-content: space-between;
	align-items: center;
	height: 88rpx;
	padding: 0 30rpx;
	background-color: #FFFFFF;
	border-bottom: 1rpx solid #F0F0F0;

	.nav-left {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;

		.back-icon {
			font-size: 48rpx;
			color: #333333;
		}
	}

	.nav-title {
		flex: 1;
		text-align: center;
		font-size: 36rpx;
		font-weight: bold;
		color: #333333;
	}

	.nav-right {
		width: 60rpx;
	}
}

/* 筛选栏 */
.filter-bar {
	background-color: #FFFFFF;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #F0F0F0;

	.filter-scroll {
		white-space: nowrap;

		.filter-item {
			display: inline-block;
			padding: 10rpx 30rpx;
			margin-left: 30rpx;
			background-color: #F5F5F5;
			border-radius: 30rpx;
			font-size: 28rpx;
			color: #666666;
			transition: all 0.3s;

			&.active {
				background-color: #E91E63;
				color: #FFFFFF;
			}
		}
	}
}

/* 红娘列表 */
.matchmaker-scroll {
	height: calc(100vh - 88rpx - 80rpx);
}

.matchmaker-list {
	padding: 20rpx 30rpx;
}

.matchmaker-card {
	display: flex;
	padding: 30rpx;
	margin-bottom: 20rpx;
	background-color: #FFFFFF;
	border-radius: 20rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	transition: transform 0.2s;

	&:active {
		transform: scale(0.98);
	}

	/* 左侧头像区 */
	.avatar-section {
		position: relative;
		margin-right: 30rpx;

		.avatar {
			width: 160rpx;
			height: 160rpx;
			border-radius: 20rpx;
			background: linear-gradient(135deg, #F5F5F5 0%, #E0E0E0 100%);
		}

		.avatar-placeholder {
			position: absolute;
			top: 0;
			left: 0;
			width: 160rpx;
			height: 160rpx;
			border-radius: 20rpx;
			background: linear-gradient(135deg, #FFE5F1 0%, #FFECF3 100%);
			display: flex;
			align-items: center;
			justify-content: center;
			border: 2rpx solid rgba(233, 30, 99, 0.1);

			.placeholder-icon {
				font-size: 80rpx;
				color: rgba(233, 30, 99, 0.3);
			}
		}

		.level-badge {
			position: absolute;
			bottom: -10rpx;
			left: 50%;
			transform: translateX(-50%);
			padding: 5rpx 15rpx;
			border-radius: 20rpx;
			font-size: 20rpx;
			color: #FFFFFF;
			white-space: nowrap;

			&.level-1 {
				background: linear-gradient(135deg, #CD7F32 0%, #8B4513 100%);
			}

			&.level-2 {
				background: linear-gradient(135deg, #C0C0C0 0%, #808080 100%);
			}

			&.level-3 {
				background: linear-gradient(135deg, #FFD700 0%, #FFA500 100%);
			}

			&.level-4 {
				background: linear-gradient(135deg, #00CED1 0%, #4682B4 100%);
			}

			&.level-5 {
				background: linear-gradient(135deg, #9370DB 0%, #8A2BE2 100%);
			}
		}
	}

	/* 右侧信息区 */
	.info-section {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 15rpx;

		.name-row {
			display: flex;
			align-items: center;
			gap: 15rpx;

			.name {
				font-size: 34rpx;
				font-weight: bold;
				color: #333333;
			}

			.type-tag {
				padding: 5rpx 15rpx;
				border-radius: 10rpx;
				font-size: 22rpx;
				color: #FFFFFF;

				&.formal {
					background-color: #E91E63;
				}

				&.parttime {
					background-color: #FF9800;
				}
			}
		}

		.stats-row {
			display: flex;
			align-items: center;
			gap: 10rpx;

			.stats-icon {
				font-size: 28rpx;
			}

			.stats-text {
				font-size: 26rpx;
				color: #666666;
			}
		}

		.location-row {
			display: flex;
			align-items: center;
			gap: 10rpx;

			.location-icon {
				font-size: 24rpx;
			}

			.location-text {
				font-size: 26rpx;
				color: #999999;
			}
		}

		.profile-row {
			.profile-text {
				font-size: 26rpx;
				color: #666666;
				line-height: 1.5;
				display: -webkit-box;
				-webkit-box-orient: vertical;
				-webkit-line-clamp: 2;
				overflow: hidden;
			}
		}

		.action-row {
			display: flex;
			gap: 20rpx;
			margin-top: 10rpx;

			.contact-btn {
				display: flex;
				align-items: center;
				gap: 10rpx;
				padding: 10rpx 30rpx;
				background-color: #4CAF50;
				border-radius: 30rpx;
				color: #FFFFFF;
				font-size: 24rpx;

				.btn-icon {
					font-size: 28rpx;
				}
			}

			.detail-btn {
				flex: 1;
				display: flex;
				align-items: center;
				justify-content: center;
				gap: 10rpx;
				padding: 10rpx 30rpx;
				background-color: #E91E63;
				border-radius: 30rpx;
				color: #FFFFFF;
				font-size: 24rpx;

				.arrow {
					font-size: 28rpx;
				}
			}
		}
	}
}

/* 加载状态 */
.load-status {
	padding: 30rpx;
	text-align: center;

	.loading-text,
	.nomore-text {
		font-size: 26rpx;
		color: #999999;
	}
}

/* 空状态 */
.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 200rpx 0;

	.empty-icon {
		font-size: 120rpx;
		margin-bottom: 30rpx;
	}

	.empty-text {
		font-size: 28rpx;
		color: #999999;
	}
}

/* 底部占位 */
.bottom-placeholder {
	height: 20rpx;
}
</style>

